package LC;

import java.lang.ref.PhantomReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName TestThread
 * @Description: TODO  交替打印奇数偶数
 * @Author hl
 * @Date 2020/8/4
 * @Version V1.0
 **/
public class TestThread {
    private static  AtomicInteger  num=new AtomicInteger(1);
    private static CountDownLatch countDownLatch=new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {

        ArrayList<Integer> list=new ArrayList<>();

        Thread t1 =new Thread(()->{
            System.out.println(Thread.currentThread().getName());
            while(num.intValue()<100){
                if(num.intValue()%2==1){
                    System.out.println("奇数线程"+num);
                    num.getAndIncrement();
                }
                countDownLatch.countDown();
            }
        });

     Thread t2=new Thread(()->{
         System.out.println(Thread.currentThread().getName());
         while (num.intValue()<=100){
             if(num.intValue()%2==0){
                 System.out.println("偶数线程:"+num);
                 num.getAndIncrement();
             }
            countDownLatch.countDown();
         }
     });
     t1.start();
     t2.start();
     countDownLatch.await();
    }
}
class TestThread1{

    public static int i=1;
    public static final int total=100;
    public static Object lock=new Object();

    public static void main(String[] args) {
        Thread t1=new Thread(()->{
            System.out.println(1);
            while(i<=total){
            synchronized (lock){
                if(i%2==1){
                    System.out.println("奇数线程打印"+i++);
                    lock.notify();
                }else{
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            }
        });
        Thread t2=new Thread(()->{
            System.out.println(2);
            while(i<=total){
                synchronized (lock){
                    if(i%2==0){
                        System.out.println("偶数线程打印"+i++);
                        lock.notify();
                    }else{
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        t1.start();
        t2.start();


    }






}
